package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Reply extends Activity {
	
	// Declare our Views, so we can access them later
	private TextView title;
	private TextView text;
	private TextView time;
	private EditText reply;
	private Button btnReply;
	private TextView lblResult;
	
	private String titleB;
	private String textB;
	private String timeB;
	private String P_id;
	private String catB;
	private String id;
	private String U_id;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.reply);

		// Get the EditText and Button References
		title = (TextView)findViewById(R.id.title);
		text = (TextView)findViewById(R.id.text);
		time = (TextView)findViewById(R.id.time);
		lblResult = (TextView)findViewById(R.id.result);
		
		reply = (EditText)findViewById(R.id.reply);
		btnReply = (Button)findViewById(R.id.reply_button);
		
		SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
        id = user.getString("CurrentUser", null);
		
		//IF PARAMETERS HAVE BEEN SUCCESSFULLY PASSED
		Bundle extras = getIntent().getExtras();
		if(extras !=null)
		{
			titleB = extras.getString("title");
			title.setText(titleB);
			
			textB = extras.getString("text");
			text.setText(textB);
			
			U_id = extras.getString("U_id");
			
	        String u = getUsername(U_id);
			String name[];
			name = u.split("@");
			String username = name[0];
			
			timeB = extras.getString("time");
			time.setText("Posted by "+username+" on " + timeB);
			time.setTextColor(Color.GRAY);
			
			P_id = extras.getString("id");
			catB = extras.getString("cat");
			
		}
		else{
			lblResult.setText("Error getting data!");
		}
		
		//Set Click Listener
		btnReply.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				String text = reply.getText().toString();
				
				String r = reply(P_id,id,catB,text);
				//result.setText(r);
				//Intent myIntent = new Intent(v.getContext(), BuySell.class);
				//startActivityForResult(myIntent, 0);
			
				lblResult.setText(r);
				
				Toast.makeText(
						getApplicationContext(),
						"Reply sent!",
						Toast.LENGTH_SHORT)
						.show();
				
				//Intent myIntent = new Intent(v.getContext(), TabMain.class);
				//startActivityForResult(myIntent, 0);
				finish();
			}
		});
	}
	
public static final String REPLY = "http://www.upennakpsi.org/lololol/pennmarketplace/reply.php";
	
	private String reply (String id, String U_id, String cat, String text) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();
 
		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		nameValuePairs.add(new BasicNameValuePair("cat",cat));
		nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(REPLY);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
	
public static final String USER = "http://www.upennakpsi.org/lololol/pennmarketplace/getusername.php";
	
	private String getUsername (String id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));
		//nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
		//nameValuePairs.add(new BasicNameValuePair("P_id",P_id));
		//nameValuePairs.add(new BasicNameValuePair("text",text));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(USER);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}
		
		return result;
	}
	
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//    	super.onCreateOptionsMenu(menu);
//    	MenuInflater inflater = getMenuInflater();
//    	inflater.inflate(R.menu.menu, menu);
//    	return true;
//    }
//    
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//    	switch (item.getItemId()) {
//		case R.id.preferences:
//			startActivity(new Intent(this, Prefs.class));
//			return true; 
//			
//		case R.id.logout:
//			//IMPLEMENT LOGOUT HERE
//			
//			Toast.makeText(
//					getApplicationContext(),
//					"Successfully Logged Out!",
//					Toast.LENGTH_SHORT)
//					.show();
//			Intent myIntent = new Intent(Reply.this, Intro.class);
//			startActivityForResult(myIntent, 0);
//			
//			
////			new AlertDialog.Builder(Reply.this)
////			//.setTitle(Register.this.getResources().getString(R.string.register_alert))  
////			.setMessage("Successfully Logged Out!")  
////			//.setIcon(R.drawable.book)  
////			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
////				public void onClick(DialogInterface dialog, int id) {
////					Intent myIntent = new Intent(Reply.this, Intro.class);
////					startActivityForResult(myIntent, 0);
////				}
////			})
////			.show();
//			
//			return true;
//    	}
//    	return false;
//    }

}
